# Create your views here.
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.template import RequestContext
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse
from homesite.bugs.models import Project
from homesite.bugs.models import Task
from homesite.bugs.models import History
from forms import TaskForm
from forms import HistoryForm
from forms import TaskBugForm
from forms import TaskFeatureForm

#from django.contrib.auth.decorators import permission_required
#@permission_required('polls.can_vote', login_url="/permission_denied/")



def default_proc(request):
    "A context processor."
   
    user_name = request.user
   
    return {
        'user_name': user_name,
        #'project_name': project_name,
    }



@login_required
def index(request, prjid):
    project_name = Project.objects.get(id = prjid).name
    return render_to_response('bugs/index.html', locals(), context_instance=RequestContext(request, processors=[default_proc]))



@login_required
def projectselect(request):
    projectslist = Project.objects.all()
    return render_to_response('bugs/projectselect.html', locals())



@login_required
def newbug(request, prjid):
    project_name = Project.objects.get(id = prjid).name
    if request.method == 'POST':
        form = TaskForm(request.POST)
        if form.is_valid():
            taskinst = form.save(commit=False)
            taskinst.serial = Task.objects.filter(project = prjid).count() + 1       
            taskinst.save()
            h = History(task=taskinst ,comment='Task Created', user=request.user)
            h.save();
            return HttpResponseRedirect(reverse('homesite.bugs.views.alltask', args=[prjid]))
    else:
        form = TaskForm(initial={'project':prjid, 'kind':'Bug', 'severity':'Normal','status':'Open','reporter':request.user.id,'owner':request.user.id})
    return render_to_response('bugs/form_bug_add.html', locals(), context_instance=RequestContext(request, processors=[default_proc]))



@login_required
def newfeature(request, prjid):
    project_name = Project.objects.get(id = prjid).name
    if request.method == 'POST':
        form = TaskForm(request.POST)
        if form.is_valid():
            taskinst = form.save(commit=False)
            taskinst.serial = Task.objects.filter(project = prjid).count() + 1
            taskinst.save()
            h = History(task=taskinst ,comment='Task Created', user=request.user)
            h.save();
            return HttpResponseRedirect(reverse('homesite.bugs.views.alltask', args=[prjid]))
    else:
        form = TaskForm(initial={'project':prjid, 'kind':'Feature', 'severity':'Normal','status':'New','reporter':request.user.id,'owner':request.user.id})
    return render_to_response('bugs/form_feature_add.html', locals(), context_instance=RequestContext(request, processors=[default_proc]))



@login_required
def alltask(request, prjid):
    tasklist = Task.objects.filter(project = prjid)
    project_name = Project.objects.get(id = prjid).name
    return render_to_response('bugs/task_all.html', locals(), context_instance=RequestContext(request, processors=[default_proc]))
 
@login_required 
def activetask(request, prjid): 
    project_name = Project.objects.get(id = prjid).name
    q1 = Task.objects.filter(project = prjid)
    tasklist = q1.exclude(status='Resolved')
    return render_to_response('bugs/task_active.html', locals(), context_instance=RequestContext(request, processors=[default_proc]))


@login_required 
def curusertask(request, prjid):
    project_name = Project.objects.get(id = prjid).name
    q1 = Task.objects.filter(project = prjid)
    q2 = q1.filter(owner=request.user)
    tasklist = q2.exclude(status='Resolved')
    return render_to_response('bugs/task_curuser.html', locals(), context_instance=RequestContext(request, processors=[default_proc]))


 
@login_required 
def taskinfo(request, prjid, taskid): 
    taskitem = Task.objects.get(id = taskid)
    taskhistory = History.objects.filter(task=taskid)
    project_name = Project.objects.get(id = prjid).name
    if request.method == 'POST':
        form = HistoryForm(request.POST, instance=taskitem)
        if form.is_valid():
            
            formcomment = ''
 
            if taskitem.severity !=  form.cleaned_data['severity']:
                formcomment = '- Severity changed from ' + taskitem.severity  + ' to ' + form.cleaned_data['severity']
                h = History(task=taskitem,comment=formcomment, user=request.user)
                h.save();
                
            if taskitem.owner !=  form.cleaned_data['owner']:
                formcomment = '- owner changed from ' + taskitem.owner.username + ' to ' + form.cleaned_data['owner'].username
                h = History(task=taskitem,comment=formcomment, user=request.user)
                h.save(); 
           
            if taskitem.summary !=  form.cleaned_data['summary']:
                formcomment = '- Summary changed from ' + taskitem.summary  + ' to ' + form.cleaned_data['summary']            
                h = History(task=taskitem,comment=formcomment, user=request.user)
                h.save(); 
                
            if taskitem.description !=  form.cleaned_data['description']:
                formcomment = '- Description changed from ' + taskitem.description  + ' to ' + form.cleaned_data['description']            
                h = History(task=taskitem,comment=formcomment, user=request.user)
                h.save();                 
            
            if form.cleaned_data['comment'] !=  '':
                formcomment = form.cleaned_data['comment']           
                h = History(task=taskitem,comment=formcomment, user=request.user)
                h.save();  

            # status
            status_form = form.save(commit=False)
            
            new_status = request.POST.get('new_status', '')
            if new_status != '':
                if taskitem.status !=  new_status:
         
                    formcomment = '- Status changed from ' + taskitem.status  + ' to ' + new_status            
                    h = History(task=taskitem,comment=formcomment, user=request.user)
                    h.save(); 
                    #status_form.resolution = ''
                    status_form.status = new_status 
            status_form.save()
            
            return HttpResponseRedirect(reverse('homesite.bugs.views.taskinfo', args=[prjid,taskid]))
    else:
        if taskitem.kind == 'Bug':
            form = TaskBugForm(instance=taskitem)
        else:
            form = TaskFeatureForm(instance=taskitem)

    return render_to_response('bugs/taskinfo.html', locals(), context_instance=RequestContext(request, processors=[default_proc]))





